package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"modbus-go-demo/global"
	"time"
)

func LoggerToFile() gin.HandlerFunc {

	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()
		// 处理请求
		c.Next()
		// 结束时间
		// 执行时间
		latencyTime := time.Since(startTime).String()
		// 请求方式
		reqMethod := c.Request.Method
		// 请求路由
		reqUri := c.Request.RequestURI
		// 状态码
		statusCode := c.Writer.Status()
		// 请求IP
		clientIP := c.ClientIP()

		// 日志格式
		global.MyLogger.WithFields(logrus.Fields{
			"status_code":  statusCode,
			"latency_time": latencyTime,
			"client_ip":    clientIP,
			"req_method":   reqMethod,
			"req_uri":      reqUri,
		}).Info()
	}
}

func CustomRecovery() gin.HandlerFunc {
	return gin.CustomRecovery(func(ctx *gin.Context, any interface{}) {
		defer func() {
			if err := recover(); err != nil {
				fmt.Println("log failed: ", err)
			}
		}()
		global.MyLogger.WithFields(logrus.Fields{
			"status_code": 500,
			"panic_info":  fmt.Sprintf("%s", any),
			"req_uri":     ctx.Request.RequestURI,
		}).Error()
		ctx.String(500, "%s %v", ctx.Request.RequestURI, any)
	})
}

func CheckApiLogin(ctx *gin.Context) {

}
